package com.atguigu.gmall.order.listener.mq;

import com.atguigu.gmall.common.util.JSONs;
import com.atguigu.gmall.mq.service.RabbitMqService;
import com.atguigu.gmall.mq.ware.StockResultMsg;
import com.atguigu.gmall.order.biz.OrderBizService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author lfy
 * @Description  订单扣库存结果监听
 * @create 2023-08-05 16:44
 */
@Slf4j
@Component
public class OrderStockDeductResultListener {


    @Autowired
    OrderBizService orderBizService;

    @Autowired
    RabbitMqService mqService;

    /**
     * 监听库存扣减结果队列
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(bindings={
            @QueueBinding(
                    value = @Queue(value = "queue.ware.order",durable = "true",exclusive = "false",autoDelete = "false"),
                    exchange = @Exchange(value = "exchange.direct.ware.order",autoDelete = "false",durable = "true",type = "topic"),
                    key = "ware.order"
            )
    })
    public void stockresult(Message message, Channel channel) throws IOException {

        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        String json = new String(message.getBody());
        log.info("收到库存系统扣减结果：{}",json);
        try {
            StockResultMsg msg = JSONs.jsonStr2Obj(json, StockResultMsg.class);

            //TODO 库存系统太老了，没有联动userid的功能
            orderBizService.orderDeductStatusChange(msg.getOrderId(),msg.getStatus());

            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            mqService.retry(json,deliveryTag,channel,3);

        }


    }
}
